package Andrew;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TestServer4 implements Runnable {
	static String list;
	/**
	 * Accept this many connections.
	 */
	private final int my_backlog = 5;

	/**
	 * The server socket.
	 */
	private ServerSocket my_serverSocket;

	/**
	 * Create the server socket.
	 * 
	 * @param a_port
	 *            the port that the server socket should listen on.
	 */
	public TestServer4(final int a_port) {
		try {
			my_serverSocket = new ServerSocket(a_port, my_backlog);
			System.out.println("Screen " + a_port);
		} catch (final IOException ioe) {
			ioe.printStackTrace();
		} catch (final SecurityException se) {
			se.printStackTrace();
		}
	}

	/**
	 * Method that listens on the server socket forever and prints each incoming
	 * message to the console.
	 */

	@Override
	public void run() {
		while (true) {
			try {
				final long time = System.currentTimeMillis();
				final Socket socket = my_serverSocket.accept();
				final BufferedReader in = new BufferedReader(
						new InputStreamReader(socket.getInputStream()));
				final String line = in.readLine();
				final PrintWriter out = new PrintWriter(
						socket.getOutputStream(), true);
				String outLine = out.toString();
				if (line.equalsIgnoreCase("list")) {
					out.println(Walkin.walkin(new File(
							"C:\\Documents and Settings/Andrew/Dist/")));
				} else if (line.split("->")[0].equalsIgnoreCase("play")) {

					System.out.println("playing: " + line.split("->")[1]);
					outLine = "playing->" + line.split("->")[1];
					System.out.println(outLine);
				} else if (line.split("->")[0].equalsIgnoreCase("command")) {
					outLine = "running command: " + line.split("->")[1];
				} else {
					continue;
				}
				final long time2 = System.currentTimeMillis();
				final long timeTaken = time2 - time;
				System.out.println("Request processed in: " + timeTaken + "ms");
				out.println(outLine);
			} catch (final IOException ioe) {
				ioe.printStackTrace();
			} catch (final SecurityException se) {
				se.printStackTrace();
			}
		}
	}
}
